package com.cp.admin.api.utils;

import com.alibaba.fastjson.JSONObject;
import org.bitcoinj.crypto.MnemonicCode;
import org.bitcoinj.crypto.MnemonicException;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.Keys;
import org.web3j.crypto.MnemonicUtils;

import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.util.List;

public class EthAddress {

    public static JSONObject newAddress(){
        try {
            ECKeyPair ecKeyPair = Keys.createEcKeyPair();
            String privateKey = ecKeyPair.getPrivateKey().toString(16);
            String publicKey = ecKeyPair.getPublicKey().toString(16);
            String address = Keys.getAddress(ecKeyPair);

            JSONObject jsonObject = new JSONObject();
            //System.out.println(privateKey);
            jsonObject.put("privateKey", Security.encrypt(privateKey));
            jsonObject.put("publicKey",Security.encrypt(publicKey));
            jsonObject.put("address","0x" + address);

            return jsonObject;
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<String> createWallet() throws MnemonicException.MnemonicLengthException{
        SecureRandom secureRandom = new SecureRandom();
        byte[] entropy = new byte[16];
        secureRandom.nextBytes(entropy);

        //生成12位助记词
        List<String> str = MnemonicCode.INSTANCE.toMnemonic(entropy);

        return str;
    }
}
